package com.example.attempt.utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;
public class OCR {

    public static String accurate(byte[] imgData){
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        try {
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.ccd4011644c57e88dee0349495ef3e73.2592000.1705215582.282335-45032548";

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);

            JSONObject jsonObject = new JSONObject(result);
            System.out.println(jsonObject.get("words_result"));
            String s=jsonObject.get("words_result").toString();
            JSONArray jsonArray=new JSONArray(s);
            String str="";
            for (int i=0;i<jsonArray.length();i++){
                JSONObject j=jsonArray.getJSONObject(i);
                str+=j.getString("words");
            }
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String accurate() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        try {

            String filePath = "e:\\Users\\Desktop\\SimilarityCheck\\2.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.ccd4011644c57e88dee0349495ef3e73.2592000.1705215582.282335-45032548";

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);

            JSONObject jsonObject = new JSONObject(result);
            System.out.println(jsonObject.get("words_result"));
            String s=jsonObject.get("words_result").toString();
            JSONArray jsonArray=new JSONArray(s);
            String str="";
            for (int i=0;i<jsonArray.length();i++){
                JSONObject j=jsonArray.getJSONObject(i);
                str+=j.getString("words");
            }
            System.out.println(str);
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        String text=TextIO.readFile("e:\\Users\\Desktop\\SimilarityCheck\\文档.docx");
        System.out.println("开始识别了捏");
        System.out.println(text);
    }
}
